import axios from 'axios'

let base = 'api'
const service = axios.create({
  baseURL: base,
  timeout: 20000
})

// 拦截请求数据
service.interceptors.request.use(config => {
  return config
}, error => {
  Promise.reject(error)
})

// 拦截返回数据
service.interceptors.response.use(response => {
  if (response.data.errCode === 0) {
    return Promise.resolve(response.data)
  } else {
    return Promise.reject(response)
  }
}, error => {
  return Promise.reject(error)
})

// 返回请求结果
export default function (url, method, model, params, isPost) {
  let _config = {
    url: url,
    method: method
  }
  let _params = params ? model ? model.request(JSON.parse(JSON.stringify(params))) : params : ''
  if (method.toLowerCase() === 'post' || isPost) {
    _config.data = _params
  } else {
    _config.params = _params
  }
  return new Promise((resolve, reject) => {
    return service(_config).then(response => {
      resolve(model ? model.response(response) : response)
    }).catch(error => {
      reject(error)
    })
  })
}
